package service.impl;

import dao.StuInfoMapper;
import enums.SysInfoEnum;
import exception.SysException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pojo.StuInfo;
import service.StuInfoService;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @author jesse
 * @Date 2019/5/27 09:03
 * @Version 1.0
 */
@Service
@Slf4j
public class StuInfoServiceImpl implements StuInfoService {
    @Autowired
    private StuInfoMapper mapper;

    @Override
    @Transactional
    public Integer insert(StuInfo stuInfo){
//        stuInfo
//        Optional
        log.info("stuInfo = " + stuInfo);
        if (stuInfo.getId() == null) {
            log.warn("id为空,随机生成.");
            stuInfo.setId(UUID.randomUUID().toString());
        }
        if (Optional.ofNullable(stuInfo).isPresent()) {
            return  mapper.add(stuInfo);
        }
        return 0;
    }


    @Override
    public Integer delete(String id) {

        if(Optional.ofNullable(id).isPresent()){
            return mapper.del(id);
        }
        return 0;
    }

    @Override
    public Integer update(StuInfo stuInfo) {
        if(Optional.ofNullable(stuInfo).isPresent()){
            return mapper.change(stuInfo);
        }
        return 0;
    }

    @Override
    public StuInfo getOneByStuId(Integer stuId) {
        StuInfo stuInfo = mapper.getOneByStuId(stuId);
        if(stuInfo.getStuId()==0){
            throw new SysException(SysInfoEnum.ERROR);
        }
        return stuInfo;
    }

    @Override
    public List<StuInfo> getStuByClazz(Integer clazz) {
        List<StuInfo> stuInfoOptional = mapper.getStuByClazz(clazz);
        return stuInfoOptional;
    }

    @Override
    public List<StuInfo> getAllStu() {
        List<StuInfo> stuInfos = mapper.getAllStu();
        return stuInfos;
    }

    @Override
    public List<StuInfo> getStuByArray(Integer currPage, Integer pageSize) {
        List<StuInfo> stuInfos = mapper.getAllStu();
        int firstIndex = (currPage -1 )*pageSize;
        int lastIndex = currPage * pageSize;
        if((stuInfos.size()-firstIndex)<pageSize){
            stuInfos =stuInfos.subList(firstIndex,stuInfos.size());
        }
        try{
            stuInfos = stuInfos.subList(firstIndex,lastIndex);
        }catch (Exception e){
            e.printStackTrace();
        }
        return stuInfos;
    }

    @Override
    public StuInfo getStuById(String id) {

        return mapper.getStuByid(id);
    }
}
